<template>
  <div>
    <div class="card" style="margin-bottom: 5px;">
      <el-input v-model="data.name" style="width: 300px; margin-right: 10px" placeholder="请输入宠物品种查询"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-row :gutter="20">
        <el-col :span="6" v-for="pet in data.tableData" :key="pet.id" >
          <el-card shadow="hover">
            <img :src="pet.picture" alt="宠物图片" v-if="pet.picture" style="width: 250px; height: 250px; object-fit: cover;" />
            <p><strong>宠物名称</strong> {{ pet.name }}</p>
            <p><strong>宠物品种:</strong> {{ pet.type }}</p>
            <p><strong>所属组织:</strong> {{ pet.cityName }}</p>
            <p><strong>宠物介绍:</strong> {{ pet.content }}</p>
            <div style="text-align: center;">
              <!-- 领养按钮 -->
              <el-button type="primary" @click="adoptPet(pet)" :disabled="(pet.state ===1)" v-if="data.user.role === 'USER' && !isPetAdopted(pet) " >{{ pet.state === 1 ? '已被领养' : '领养' }}</el-button>
              <!-- 取消领养按钮 -->
              <el-button type="danger" @click="cancelAdoptedPet(pet)" v-if="data.user.role === 'USER' && isPetAdopted(pet) ">取消领养</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="card">
      <el-pagination
          background
          layout="prev, pager, next"
          v-model:page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"
          @current-change="changePage"
      />
    </div>
  </div>
</template>

<script setup>
import request from "@/utils/request";
import { reactive } from "vue";
import { ElMessage } from "element-plus";

const data = reactive({
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  pageNum: 1,
  pageSize: 4,
  total: 0,
  tableData: [],
  name: null,
  cityDate: [],
});

// 分页查询
const load = () => {
  request.get('/animal/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name
    }
  }).then(res => {
    data.tableData = res.data?.list;
    data.total = res.data?.total;
  });
};

const changePage = (pageNum) => {
  data.pageNum = pageNum;
  load();
};

// 重置
const reset = () => {
  data.name = null;
  load();
};

const loadCity = () => {
  request.get('/city/selectAll').then(res => {
    if (res.code === '200') {
      data.cityDate = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 检查用户是否已经领养了该宠物
const isPetAdopted = (pet) => {
  return data.user.petssId === pet.id;
};

// 领养宠物
const adoptPet = (pet) => {
  const animalData = JSON.parse(JSON.stringify(pet));
  animalData.userId = data.user.id; // 将用户 ID 添加到宠物数据中

  // 查询用户的数据库
  request.get(`/user/selectById/${animalData.userId}`)
      .then(userResponse => {
        if (userResponse.code === '200') {
          const userData = userResponse.data;
          // 检查 petss_id 是否存在
          if (userData.petssId !== null) {
            ElMessage.warning('您已经领养过宠物，请不要贪心哦~~~');
            return; // 退出函数
          }
          // 更新用户的 petss_id 为选中的宠物 ID
          userData.petssId = animalData.id;
          // 更新宠物状态为已领养
          return request.put('/animal/updateState', { id: animalData.id, state: 1 })
              .then(() => {
                data.user.petssId = animalData.id;
                return request.put('/user/updatePetssId', { id: userData.id, petssId: userData.petssId });
              });
        } else {
          ElMessage.error('获取用户信息失败，请重试。');
        }
      })
      .then(res => {
        if (res && res.code === '200') {
          load(); // 重新加载宠物数据ElMessage.success('领养成功');
        }
      })
      .catch(err => {
        ElMessage.error('操作失败，请重试');
      });
};

// 取消领养宠物
const cancelAdoptedPet = (pet) => {
  // 提示用户确认取消领养
  ElMessageBox.confirm('取消后，宠物可能被别人领养走你确定?', '取消确认', { type: 'warning' })
      .then(() => {
        const userId = data.user.id;

        // 获取用户信息
        return request.get(`/user/selectById/${userId}`);
      })
      .then(userResponse => {
        if (userResponse.code === '200') {
          const userData = userResponse.data;

          // 清空 petssId
          userData.petssId = null;

          // 更新宠物状态为未领养
          return request.put('/animal/updateState', { id: pet.id, state: 0 })
              .then(() => {
                // 将更新后的用户数据发送到服务器
                data.user.petssId = null;
                return request.put('/user/updatePetssId', { id: userData.id, petssId: userData.petssId });
              });
        } else {
          ElMessage.error('获取用户信息失败，请重试。');
          throw new Error('用户信息获取失败'); // 抛出错误以进入下一个 catch
        }
      })
      .then(res => {
        if (res && res.code === '200') {
          load(); // 重新加载宠物数据
          ElMessage.success('取消领养成功');
        } else {
          ElMessage.error('更新用户信息失败，请重试。');
        }
      })
      .catch(err => {
      });
};

loadCity();
load();
</script>